<template>
  <div class="relative h-full">
    <div class="absolute left-5 top-4 z-30" @click="visible = true">
      <Category color="#fff" width="1.5rem" height="1.5rem" />
    </div>
    <Navbar
      v-model:visible="visible"
      :dataSource="videoList"
      @select="selectMenu"
      @update:visible="changeVisible"
    />
    <Loading
      :visible="videoLoadConfig.loading"
      :cover="videoLoadConfig.cover"
      :status="videoLoadConfig.isClick"
      @submit="handleClick"
    ></Loading>
    <div class="absolute inset-0 overflow-hidden">
      <nut-swiper
        :init-page="currSwiperIndex"
        :is-stop-propagation="false"
        auto-play="0"
        direction="vertical"
        class="h-full"
        @change="swiperChange"
        :pagination-visible="false"
      >
        <nut-swiper-item v-for="(item, index) in swiperList" :key="index">
          <div class="bg-gray-7 h-full flex items-center">
            <video
              class="w-full h-full"
              :id="'video' + index"
              controls
              @canplay="canplay"
              @ended="videoEnd"
              @durationchange="canplay"
              :src="item.videoUrl"
            ></video>
          </div>
        </nut-swiper-item>
      </nut-swiper>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Category } from "@nutui/icons-vue";
import * as owVideoAPI from "@/api/official-website/video";
import Navbar from "./components/nav-bar.vue";
import Loading from "./components/loading.vue";
import { useMallStore } from "@/store/modules/mall";
import { useRoute, useRouter } from "vue-router";
const mallStore = useMallStore();
const route = useRoute();
const videoIndex = ref<number>(0); // 视频当前索引
const swiperIndex = ref<number>(0); // swiper当前索引
const visible = ref<boolean>(false); // 菜单弹窗
const currSwiperIndex = ref<number>(0); // 控制swiper切换的索引
const videoLoadConfig = ref<{
  loading: boolean;
  isClick: boolean;
  isLoad: boolean;
  cover: string;
}>({
  loading: false, // 控制遮罩显示隐藏
  isClick: false, // 是否点击遮罩的播放按钮
  isLoad: false, // 视频是否加载完成
  cover: "", // 封面
});
const videoList = ref<WebVideo[]>([]);
const swiperList = ref([]);

const loadData = () => {
  // 请求数据
  owVideoAPI.list().then((res) => {
    videoList.value = res.data;
    swiperList.value = videoList.value.slice(0, 3);
    videoLoadConfig.value.loading = true; // 显示遮罩层
    videoLoadConfig.value.cover = res.data[0].videoCoverUrl;
  });
};

watch(
  () => route.fullPath,
  (newVal) => {
    if (newVal === "/" && !videoList.value?.length) loadData();
  }
);
loadData();

const getPrevIndex = (index, len) => (index - 1 + len) % len;

const getNextIndex = (index, len) => (index + 1) % len;

// 控制菜单关闭和显示
const changeVisible = (val) => (visible.value = val);

// 点击遮罩弹窗的播放按钮
const handleClick = () => {
  const _instance = videoInstance(swiperIndex.value);
  _instance.play();
  videoLoadConfig.value.isClick = true;
};

// 视频准备就绪，可以播放
const canplay = () => (videoLoadConfig.value.isLoad = true);

// 监听遮罩弹窗
watch(
  [() => videoLoadConfig.value.isClick, () => videoLoadConfig.value.isLoad],
  ([isClick, isLoad]) => {
    if (isClick && isLoad) {
      videoLoadConfig.value.loading = false;
    } else {
      videoLoadConfig.value.loading = true;
    }
  }
);

// 更新swiperList
const updateSwiperList = () => {
  // 找到swiper上一个，下一个的索引
  const sPrevI = getPrevIndex(swiperIndex.value, 3);
  const sNextI = getNextIndex(swiperIndex.value, 3);

  // 找到video上一个，下一个的索引
  const vPrevI = getPrevIndex(videoIndex.value, videoList.value.length);
  const vNextI = getNextIndex(videoIndex.value, videoList.value.length);

  // 计算swiperList
  const result = [];
  result[swiperIndex.value] = videoList.value[videoIndex.value];
  result[sPrevI] = videoList.value[vPrevI];
  result[sNextI] = videoList.value[vNextI];
  return result;
};

// 滑动后回调
const swiperChange = (index: number) => {
  // 更新当前swiper索引和视频索引，触发swiperList更新
  const old = swiperIndex.value;
  swiperIndex.value = index;
  if (swiperIndex.value === getNextIndex(old, 3)) {
    // 下滑
    videoIndex.value = getNextIndex(videoIndex.value, videoList.value.length);
  } else if (swiperIndex.value === getPrevIndex(old, 3)) {
    // 上滑
    videoIndex.value = getPrevIndex(videoIndex.value, videoList.value.length);
  }
  // 更新swiperList
  swiperList.value = updateSwiperList();
  // 滑动后，当前暂停播放， 播放下一个
  videoInstance(old).pause();
  videoInstance(swiperIndex.value).play();

  if (currSwiperIndex.value <= 0) {
    currSwiperIndex.value = 1;
  }
};

// 视频实例
const videoInstance = (() => {
  let _instanceList = [];
  return function (index) {
    let _instance = _instanceList[index];
    if (!_instance) {
      let video = document.getElementById("video" + index);
      _instanceList[index] = video;
      return video;
    } else {
      return _instance;
    }
  };
})();

// 视频播放结束
const videoEnd = () => {
  // 结束后切换到下一个swiper，因为没有交互，无法自动播放
  videoIndex.value = getNextIndex(videoIndex.value, videoList.value.length); // 获取下一个索引
  swiperIndex.value = getNextIndex(swiperIndex.value, 3); // 获取下一个索引
  swiperList.value = updateSwiperList();
  currSwiperIndex.value = swiperIndex.value;
};

// 点击菜单
const selectMenu = (index: number) => {
  if (videoIndex.value == index) return;
  videoIndex.value = index; // 切换当前视频
  swiperList.value = updateSwiperList(); // 更新swiperList
  videoLoadConfig.value.isClick = false;
  videoLoadConfig.value.isLoad = false;
  videoLoadConfig.value.cover = videoList.value[index].videoCoverUrl;
};

onMounted(() => {
  let userId = route.query.uid as string;
  mallStore.setSignUserId(userId);
});

onActivated(() => {
  swiperList.value = videoList.value.slice(0, 3);
  videoIndex.value = 0;
  swiperIndex.value = 0;
  currSwiperIndex.value = 0;
  videoLoadConfig.value.loading = true; // 显示遮罩层
  videoLoadConfig.value.isClick = false;
  videoLoadConfig.value.isLoad = false;
});
</script>
